<template>
  <div
    class="node node-condition"
    :style="
      {
        '--node-color': primaryColor,
        '--node-color-strong': primaryStrong,
        '--node-bg-soft': softBg,
        '--node-shadow': shadowRgba,
      } as any
    "
  >
    <div class="node-bar"></div>
    <div class="node-content">
      <div class="node-main">
        <!-- 悬停工具栏（删除） -->
        <NodeToolbar
          :node-id="id"
          :show-execute="false"
          :show-mute="false"
          :show-delete="true"
        />
        <div class="node-title">{{ data.label || "条件节点" }}</div>
        <div class="node-desc">{{ data.description || "条件判断分支" }}</div>
        <div class="node-branches">
          <div
            v-for="branch in data.branches"
            :key="branch.id ?? branch.name"
            class="node-branch"
          >
            <span class="branch-label">{{ branch.name }}</span>
            <span class="branch-sep">｜</span>
            <span class="branch-cond">{{ formatBranchCondition(branch) }}</span>
          </div>
        </div>
        <!-- 出参展示：value : key，整体右对齐 -->
        <div
          v-if="outputsPairs.length"
          class="kv-list kv-right"
          style="margin-top: 6px"
        >
          <div v-for="it in outputsPairs" :key="it.key" class="kv-item">
            <span class="kv-val">{{ it.key }}</span>
            <span class="kv-sep">:</span>
            <span class="kv-key">{{ it.value }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 左侧连接点 -->
    <Handle
      type="target"
      :position="Position.Left"
      id="target"
      class="node-handle node-handle-left"
    />
    <!-- 右侧目标连接点：用于支持根据卡片右半自动吸附到右侧目标点 -->
    <Handle
      type="target"
      :position="Position.Right"
      id="target-right"
      class="node-handle node-handle-right"
    />
    <!-- 右侧连接点：按分支数量生成多个句柄；若无分支则提供一个默认句柄 -->
    <template v-if="data.branches && data.branches.length > 0">
      <Handle
        v-for="(branch, idx) in data.branches || []"
        :key="`source-${branch.id ?? idx}`"
        type="source"
        :position="Position.Right"
        :id="`source-${branch.id ?? idx}`"
        class="node-handle node-handle-right"
        :style="styleForBranch(idx, (data.branches || []).length)"
      />
    </template>
    <template v-else>
      <Handle
        type="source"
        :position="Position.Right"
        id="source"
        class="node-handle node-handle-right"
        :style="{ top: '50%' }"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
import { defineProps, computed } from "vue";
import { Handle, Position } from "@vue-flow/core";
import NodeToolbar from './NodeToolbar.vue'

interface Branch {
  id?: string;
  name: string;
  condition?: string;
  conditionData?: {
    mode: "rules" | "formula";
    logicalOperator?: "and" | "or";
    rules?: Array<{
      field: string;
      operator: string;
      value?: string;
      selectedCount?: number;
    }>;
    formula?: string;
  };
}

interface Props {
  id?: string;
  data: {
    label?: string;
    description?: string;
    branches?: Branch[];
    outputs?: Array<{ key: string; name?: string }>;
  };
}

const props = defineProps<Props>();

// 分类颜色表（与 nodePanelDrawer.vue 保持一致）
const catColors: Record<string, string> = {
  form: "#3b82f6",
  approval: "#f59e42",
  basic: "#10b981",
  custom: "#a855f7",
  condition: "#f43f5e",
  control: "#6366f1",
};

function hexToRgb(hex: string): { r: number; g: number; b: number } | null {
  const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  if (!m) return null;
  return {
    r: parseInt(m[1], 16),
    g: parseInt(m[2], 16),
    b: parseInt(m[3], 16),
  };
}

function rgba(hex: string, a: number): string {
  const rgb = hexToRgb(hex);
  if (!rgb) return hex;
  const { r, g, b } = rgb;
  return `rgba(${r}, ${g}, ${b}, ${a})`;
}

// 主色：优先 data.category，否则按逻辑节点默认红
const primaryColor = computed(() => {
  const cat = (props as any).data?.category as string | undefined;
  if (cat && catColors[cat]) return catColors[cat];
  return catColors.logic; // 兼容旧条件节点默认红
});

const primaryStrong = computed(() => primaryColor.value);
const softBg = computed(() => rgba(primaryColor.value, 0.06));
const shadowRgba = computed(() => rgba(primaryColor.value, 0.08));

// 计算每个分支句柄在右侧的垂直分布位置
function styleForBranch(index: number, total: number) {
  if (total <= 1) {
    return { top: "50%" };
  }
  // 将 0..total-1 映射为 20%..80% 的相对位置
  const min = 20;
  const max = 80;
  const step = (max - min) / (total - 1);
  const topPct = min + step * index;
  return { top: `${topPct}%` };
}

// 出参对（按 value key 顺序渲染），value 显示为占位符 ${节点名称,key}，key 显示为出参 key
const outputsPairs = computed(() => {
  const list = Array.isArray((props as any).data?.outputs)
    ? ((props as any).data?.outputs as Array<any>)
    : [];
  const label = String(((props as any).data?.label || "") as string);
  return list
    .filter((it) => it && String(it.key || "").trim() !== "")
    .map((it) => {
      const key = String(it.key);
      return { key, value: `\${${label},${key}}` };
    });
});

// 显示条件的中文格式化
const FIELD_LABELS: Record<string, string> = {
  leaveDays: "请假天数",
  department: "发起部门",
  amount: "金额",
  status: "状态",
};

const OP_LABELS: Record<string, string> = {
  equals: "等于",
  notEquals: "不等于",
  greaterThan: "大于",
  greaterThanOrEqual: "大于等于",
  lessThan: "小于",
  lessThanOrEqual: "小于等于",
  contains: "包含",
  belongsTo: "属于",
};
function formatRule(rule: any): string {
  const field = String(rule?.field ?? "");
  const op = OP_LABELS[rule?.operator] || String(rule?.operator ?? "");
  const value = String(rule?.value ?? "");
  return `${field}${op}${value}`;
}

function formatBranchCondition(branch: Branch): string {
  const cd: any = (branch as any).conditionData;
  if (cd && cd.mode === "rules") {
    const rules = Array.isArray(cd.rules) ? cd.rules : [];
    if (rules.length === 0) return "未设置条件";
    const glue = cd.logicalOperator === "and" ? " 且 " : " 或 ";
    return rules.map((r: any) => formatRule(r)).join(glue);
  }
  if (cd && cd.mode === "formula") {
    const text = String(cd.formula || "").trim();
    return text || "未设置条件";
  }
  // 兼容旧结构：直接使用 branch.conditionRules 与 branch.logicalOperator
  const legacyRules: any[] = Array.isArray((branch as any).conditionRules)
    ? ((branch as any).conditionRules as any[])
    : [];
  if (legacyRules.length > 0) {
    const legacyGlue =
      (branch as any).logicalOperator === "and" ? " 且 " : " 或 ";
    return legacyRules.map((r: any) => formatRule(r)).join(legacyGlue);
  }
  const legacy = String((branch as any).condition || "").trim();
  return legacy || "未设置条件";
}

// 删除事件由 NodeToolbar 内部处理
</script>

<style scoped>
.node {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px var(--node-shadow, rgba(0, 0, 0, 0.08));
  min-width: 240px;
  max-width: 360px;
  border: 1.5px solid #e5e7eb;
  overflow: visible;
  margin: 0;
  padding: 0;
  transition:
    box-shadow 0.2s,
    border 0.2s;
  cursor: pointer;
  position: relative;
}

/* 悬停时显示来自子组件的工具栏 */
.node:hover :deep(.node-toolbar) {
  display: flex;
}

.node-bar {
  width: 8px;
  background: var(--node-color, #f43f5e);
  border-top-left-radius: 14px;
  border-bottom-left-radius: 14px;
}

.node-content {
  display: flex;
  align-items: flex-start;
  padding: 14px 10px 14px 16px;
  flex: 1;
}

.node-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.node-title {
  font-weight: 600;
  color: var(--node-color-strong, #b91c1c);
  font-size: 16px;
  margin-bottom: 2px;
}

.node-desc {
  color: var(--node-color, #f43f5e);
  font-size: 13px;
  line-height: 1.3;
  margin-bottom: 8px;
}

.node-branches {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.node-branch {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  background: var(--node-bg-soft, #fef2f2);
  border-radius: 6px;
  padding: 3px 8px;
  margin-bottom: 2px;
}

.branch-label {
  color: var(--node-color-strong, #b91c1c);
  font-weight: 500;
}

.branch-sep {
  color: var(--node-color, #e11d48);
  opacity: 0.55;
}

.branch-cond {
  color: #64748b;
  font-size: 12px;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 连接点样式 */
.node-handle {
  width: 12px !important;
  height: 12px !important;
  background: var(--node-color, #f43f5e) !important;
  border: 2px solid #fff !important;
  border-radius: 50% !important;
  position: absolute !important;
  transform: translate(-50%, -50%) !important;
}

.node-handle-left {
  left: -6px !important;
  top: 50% !important;
}

.node-handle-right {
  right: -6px !important;
  top: 50% !important;
}

.node-handle:hover {
  background: var(--node-color-strong, #dc2626) !important;
  transform: translate(-50%, -50%) scale(1.2) !important;
}

/* key-value 列表样式，与其他节点保持一致 */
.kv-list {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.kv-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #64748b;
}
.kv-key {
  color: var(--node-color, #f43f5e);
}
.kv-val {
  color: #0f172a;
}
.kv-sep {
  opacity: 0.5;
}
/* 右对齐 */
.kv-right {
  align-items: flex-end;
}
.kv-right .kv-item {
  justify-content: flex-end;
}
</style>
